package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    /**
     * 根据查询数据 进行分页 并排序 查看商品详情信息
     * @param key
     * @param page
     * @param rows
     * @param sorBy
     * @param desc
     * @return
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(
            @RequestParam(value = "key",required = false)String key,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "5")Integer rows,
            @RequestParam(value = "sortBy",required = false)String sorBy,
            @RequestParam(value = "desc",required = false)Boolean desc
    ){
      PageResult<Brand> result =  brandService.queryBrandByPage(key,page,rows,sorBy,desc);
        if (null == result || CollectionUtils.isEmpty(result.getItems())) {
            //404
            return ResponseEntity.notFound().build();
        }
        return  ResponseEntity.ok(result);
    }

    /**
     * 新增商品
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand,@RequestParam("cids")List<Long> cids){

        brandService.saveBrand(brand,cids);
        //  HttpStatus.CREATED  201 请求成功
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 新增商品  选择商品分类
     */
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandsByCid(@PathVariable("cid")Long cid){

      List<Brand> list =  brandService.queryBrandsByCid(cid);
        if (list==null || CollectionUtils.isEmpty(list)) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(list);
    }
    /**
     * 根据id查询品牌
     */
    @GetMapping("{id}")
    public ResponseEntity<Brand> queryBrandById(@PathVariable("id") Long id){
      Brand brand =  brandService.queryBrandById(id);
        if (brand==null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(brand);
    }
}
